import 'dart:async';

import 'package:bot_toast/bot_toast.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_modular/flutter_modular.dart';
import 'package:thinking/event/_.dart';
import 'package:thinking/service/_.dart';
import 'package:thinking/utils/_.dart';
import 'package:thinking/config/_.dart';
import 'package:thinking/views/TopicView/TopicClassLeft.dart';
import 'package:thinking/widget/_.dart';
import 'package:thinking/entity/_.dart';

class TopicClass extends StatefulWidget {
  @override
  _TopicClass createState() => _TopicClass();
}

class _TopicClass extends State<TopicClass> {
  late Future<dynamic> _function;
   EasyRefreshController _easyRefreshController = EasyRefreshController();
  int index = SPreferences().getInt('topicClassIndex') == 0
      ? 2
      : SPreferences().getInt('topicClassIndex');
  late List<TagClassIndex> _tagClassIndexList;
  List<TagClassPageEntity> _tagClassPageList = [];
  List<List<Tag>> _tagAllList = [];
  late StreamSubscription _streamSubscription;
  @override
  void initState() {
    super.initState();

    _function = future();
      _streamSubscription =   Config.eventBus.on<TopicClassEvent>().listen((event) async {
        _tagAllList[0] = [];
        _tagClassPageList[0].setIsLoad = false;
        _tagClassPageList[0].setCanLoad = true;
        _tagClassPageList[0].setPage = 0;
        _tagAllList[2] = [];
        _tagClassPageList[2].setIsLoad = false;
        _tagClassPageList[2].setCanLoad = true;
        _tagClassPageList[2].setPage = 0;
        if (event.update) {
          if(event.index!=0 && event.index!=2){
            _tagAllList[event.index] = [];
            _tagClassPageList[event.index].setCanLoad = true;
            _tagClassPageList[event.index].setIsLoad = false;
            _tagClassPageList[event.index].setPage = 0;
          }
          if (event.isHot) {
            _tagAllList[1] = [];
            _tagClassPageList[1].setCanLoad = true;
            _tagClassPageList[1].setIsLoad = false;
            _tagClassPageList[1].setPage = 0;
          }
          setState(() {

          });
          await getIndexAllTopic();
        }

    });

  }

  @override
  void dispose() {
    _streamSubscription.cancel();
    _easyRefreshController.dispose();

    super.dispose();
  }

  future() async {
    await getTagClassList();
    _tagClassIndexList.forEach((element) =>
        {_tagClassPageList.add(TagClassPageEntity()), _tagAllList.add([])});
    await this.getIndexAllTopic();
  }

  getIndexAllTopic() async {
    List<Tag> res = await TopicService.getIndexAllTopic(params: {
      "topic_Index": index,
      "topic_Page": _tagClassPageList[index].page,
      "topic_Num": _tagClassPageList[index].count,
      "user_Id": SPreferences().getInt('user_Id')
    });
    if (!_tagClassPageList[index].canLoad) {
      BotToast.showText(text: '没有更多话题了哦~');
    } else {
      _tagAllList[index] = [..._tagAllList[index], ...res];
    }
    if (res.length < _tagClassPageList[index].count &&
        _tagClassPageList[index].canLoad) {
      _tagClassPageList[index].setPage = _tagClassPageList[index].page + 1;
      _tagClassPageList[index].setCanLoad = false;
    }
    _tagClassPageList[index].setIsLoad = true;
    setState(() {});
  }

  Widget easyRefresh(Widget child) {
    return EasyRefresh(
      child: child,
      header: BezierCircleHeader(backgroundColor: ColorConfig.ThemeColor),
      footer: BezierBounceFooter(backgroundColor: ColorConfig.ThemeColor),
      enableControlFinishRefresh: false,
      enableControlFinishLoad: true,
      controller: _easyRefreshController,
      bottomBouncing: true,
      onLoad: () async {
        if (_tagClassPageList[index].canLoad) {
          _tagClassPageList[index].setPage = _tagClassPageList[index].page + 1;
        }

        await getIndexAllTopic();
        _easyRefreshController.finishLoad(success: true);
      },
    );
  }

  Future<void> getTagClassList() async {
    _tagClassIndexList = await TopicService.getAllTagClass(params: {});
    _tagClassIndexList.insertAll(0, [
      TagClassIndex.fromJson({"tagClass_Id": 0, "tagClass_Name": '我的订阅'}),
      TagClassIndex.fromJson({"tagClass_Id": 1, "tagClass_Name": '热门'}),
      TagClassIndex.fromJson({"tagClass_Id": 2, "tagClass_Name": '全部'})
    ]);
  }

  Panel search() {
    return Panel(
      top: 0,
      bottom: 0,
      child: Row(
        mainAxisAlignment: MainAxisAlignment.start,
        children: [
          IconButton(
            onPressed: () async {
              await SPreferences().setInt('topicClassIndex', index);
              Modular.to.pop();
            },
            icon: Icon(
              Icons.arrow_back,
              color: ColorConfig.BlackObsBackColor,
            ),
          ),
          Expanded(
              child: GestureDetector(
                  child: ShowSearchWidget(
                    backgroundColor: ColorConfig.LineColor,
                    textColor: ColorConfig.TextColor,
                    textVal: '搜索话题',
                  ),
                  onTap: () {
                    Modular.to.pushNamed('/indexSearch/2');
                  })),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        child: Scaffold(
          backgroundColor: ColorConfig.WhiteBackColor,
          appBar: AppBar(
            automaticallyImplyLeading: false,
            titleSpacing: 0,
            elevation: 0,
            toolbarHeight: Screen.setHeight(60),
            backgroundColor: ColorConfig.WhiteBackColor,
            title: search(),
          ),
          body: FutureBuilder(
            future: _function,
            builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
              return snapshot.connectionState == ConnectionState.done
                  ? Empty(
                      child: Container(
                        height: Screen.height(context) -
                            Screen.setHeight(60) -
                            Screen.setHeight(10),
                        child: Row(
                          children: [
                            Container(
                              width: Screen.setWidth(90),
                              color: ColorConfig.LineColor,
                              child: MediaQuery.removePadding(
                                  removeTop: true,
                                  context: context,
                                  child: ListView(
                                    shrinkWrap: true,
                                        physics: BouncingScrollPhysics(),
                                        children: _tagClassIndexList
                                            .asMap()
                                            .keys
                                            .map((e) => GestureDetector(
                                                  onTapDown: (TapDownDetails
                                                      details) async {
                                                    if (index == e) return;
                                                    setState(() {
                                                      index = e;
                                                    });
                                                    if (_tagClassPageList[index]
                                                            .isLoad ==
                                                        false)
                                                      await getIndexAllTopic();
                                                  },
                                                  child: TopicClassLeft(
                                                      isClick: index == e
                                                          ? true
                                                          : false,
                                                      topicClass:
                                                          _tagClassIndexList[e],
                                                      id: e,
                                                      topicClassWidth: 90,
                                                      backgroundColor:
                                                          ColorConfig
                                                              .WhiteBackColor,
                                                      textColor: index == e
                                                          ? ColorConfig
                                                              .ThemeColor
                                                          : ColorConfig
                                                              .BlackObsBackColor),
                                                ))
                                            .toList(),
                                      )
                                  ),
                            ),
                            Container(
                               width:
                               Screen.width(context) - Screen.setWidth(90),
                               child: MediaQuery.removePadding(
                                   removeTop: true,
                                   context: context,
                                   child: _tagClassPageList[index].isLoad
                                       ? easyRefresh(Empty(
                                     child: ListView(
                                       shrinkWrap: true,
                                       physics: BouncingScrollPhysics(),
                                       children: _tagAllList[index]
                                           .map((e) => GestureDetector(
                                         onTap: (){

                                           Modular.to.pushNamed('/topicIndex/${e.id}/${e.tagTitle}/${e.isSub!?1:0}');
                                         },
                                         child: TopicItemWidget(
                                           isUpdate: false,
                                           isShowButton: index == 0
                                               ? false
                                               : true,
                                           tagData: e,
                                           type: 1,
                                           key: ValueKey(e.id),
                                         ),
                                       ))
                                           .toList(),
                                     ),
                                     isShow:
                                     _tagAllList[index].length == 0,
                                   ))
                                       : Loading()),
                             )
                          ],
                        ),
                      ),
                      isShow: _tagClassIndexList.length == 0,
                    )
                  : Loading();
            },
          ),
        ),
        onWillPop: () async {
          await SPreferences().setInt('topicClassIndex', index);
          return true;
        });
  }
}
